"""Telegram通知服务"""

import aiohttp
import asyncio
from typing import List, Dict, Any, Optional
from app.config import settings
from app.utils.logger import get_monitor_logger


class TelegramService:
    """Telegram通知服务类"""
    
    def __init__(self):
        self.bot_token = getattr(settings, 'TELEGRAM_BOT_TOKEN', None)
        self.api_base_url = f"https://api.telegram.org/bot{self.bot_token}"
        self.logger = get_monitor_logger()
    
    async def send_message(self, chat_id: str, message: str, parse_mode: str = "HTML", verify_ssl: bool = False) -> bool:
        """发送Telegram消息"""
        if not self.bot_token:
            self.logger.error("❌ Telegram Bot Token未配置")
            return False
            
        max_retries = 3
        retry_delay = 2
        
        for attempt in range(max_retries):
            try:
                if attempt > 0:
                    self.logger.info(f"📱 Telegram消息发送重试 {attempt}/{max_retries-1}: {chat_id}")
                    await asyncio.sleep(retry_delay * attempt)
                
                url = f"{self.api_base_url}/sendMessage"
                payload = {
                    "chat_id": chat_id,
                    "text": message,
                    "parse_mode": parse_mode,
                    "disable_web_page_preview": False
                }
                
                # 创建客户端会话，根据verify_ssl参数决定是否验证SSL证书
                connector = aiohttp.TCPConnector(verify_ssl=verify_ssl)
                async with aiohttp.ClientSession(connector=connector) as session:
                    async with session.post(url, json=payload, timeout=30) as response:
                        if response.status == 200:
                            result = await response.json()
                            if result.get("ok"):
                                self.logger.info(f"✅ Telegram消息发送成功: {chat_id}")
                                return True
                            else:
                                self.logger.error(f"❌ Telegram API返回错误: {result.get('description')}")
                        else:
                            self.logger.error(f"❌ Telegram API请求失败: HTTP {response.status}")
                            
            except Exception as e:
                self.logger.error(f"❌ Telegram消息发送失败 (尝试 {attempt+1}/{max_retries}): {e}")
                
                if attempt == max_retries - 1:
                    self.logger.error(f"❌ Telegram发送最终失败: {type(e).__name__}: {str(e)}")
        
        return False
    
    async def send_product_notification(self, chat_id: str, products: List[Dict[str, Any]], 
                                      notification_subject: str, monitor_type: str = "keyword", verify_ssl: bool = False) -> bool:
        """发送商品通知到Telegram"""
        try:
            if not products:
                self.logger.warning("⚠️ 没有商品数据，跳过Telegram通知")
                return False
            
            # 构建消息内容
            message = self._build_product_message(products, notification_subject, monitor_type)
            
            # 发送消息，传递verify_ssl参数
            return await self.send_message(chat_id, message, verify_ssl=verify_ssl)
            
        except Exception as e:
            self.logger.error(f"❌ Telegram商品通知发送异常: {e}")
            return False
    
    def _build_product_message(self, products: List[Dict[str, Any]], 
                              notification_subject: str, monitor_type: str) -> str:
        """构建商品通知消息"""
        try:
            # 消息头部
            if monitor_type == "keyword":
                header = f"🔥 <b>关键词监控通知</b>\n关键词: <code>{notification_subject}</code>\n"
            elif monitor_type == "seller":
                header = f"🔥 <b>卖家监控通知</b>\n卖家: <code>{notification_subject}</code>\n"
            elif monitor_type == "shop":
                header = f"🔥 <b>店铺监控通知</b>\n店铺: <code>{notification_subject}</code>\n"
            else:
                header = f"🔥 <b>商品监控通知</b>\n监控: <code>{notification_subject}</code>\n"
            
            header += f"发现 <b>{len(products)}</b> 个新商品:\n\n"
            
            # 商品列表（最多显示5个）
            message_parts = [header]
            
            for i, product in enumerate(products[:5]):
                product_name = product.get('name', product.get('title', '未知商品'))
                product_price = product.get('price', 0)
                product_url = product.get('url', product.get('product_url', ''))
                seller_name = product.get('seller_name', product.get('seller', '未知卖家'))
                
                # 格式化价格
                if isinstance(product_price, (int, float)):
                    price_text = f"¥{product_price:,.0f}"
                else:
                    price_text = f"¥{product_price}"
                
                # 商品信息
                product_info = f"<b>{i+1}. {product_name}</b>\n"
                product_info += f"💰 价格: {price_text}\n"
                product_info += f"👤 卖家: {seller_name}\n"
                
                if product_url:
                    product_info += f"🔗 <a href=\"{product_url}\">查看商品</a>\n"
                
                product_info += "\n"
                message_parts.append(product_info)
            
            # 如果商品数量超过5个，显示提示
            if len(products) > 5:
                message_parts.append(f"... 还有 {len(products) - 5} 个商品\n\n")
            
            # 消息尾部
            footer = f"⏰ 通知时间: {self._get_current_time()}\n"
            footer += "📱 来自煤炉监控系统"
            message_parts.append(footer)
            
            return "".join(message_parts)
            
        except Exception as e:
            self.logger.error(f"❌ 构建Telegram消息失败: {e}")
            return f"🔥 发现 {len(products)} 个新商品\n监控: {notification_subject}\n⏰ {self._get_current_time()}"
    
    def _get_current_time(self) -> str:
        """获取当前时间字符串"""
        from datetime import datetime
        return datetime.now().strftime("%Y-%m-%d %H:%M:%S")